package com.xx.job.controller.system;

import com.xx.job.common.Result;
import com.xx.job.common.util.*;
import com.xx.job.controller.base.BaseController;
import com.xx.job.controller.dto.SystemUserDTO;
import com.xx.job.entity.base.BaseEntity;
import com.xx.job.entity.system.SysUser;
import com.xx.job.service.system.SysSettingService;
import com.xx.job.service.system.SysUserService;
import com.xx.job.service.system.impl.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "登陆")
public class LoginController extends BaseController {

    @Autowired
    private SysSettingService sysSettingService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private LoginService loginService;




    /**
     * 验证码
     * @param session
     * @return  base64图片信息
     * @throws Exception
     */
    @RequestMapping("/api/v1/getCaptcha")
    public Result getCaptcha()throws Exception{
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        ValidateCodeUtil.Validate v = ValidateCodeUtil.getRandomCode();
        //直接调用静态方法，返回验证码对象
        if(v!=null){
            session.setAttribute("validate", MD5Util.MD5(v.getValue().toLowerCase()));	//将验证码值保存session
            return  Result.success(v.getBase64Str());
        }
        return Result.error("返回错误");
    }

    /**
     * 登录页Logo
     * @return Logo信息
     * @throws Exception
     * // F:\data\workspase\activiti-app\src\main\resources\img\go-admin.png
     */
    @RequestMapping("/api/v1/setting")
    public Result setting()throws Exception{
        BaseEntity setting = sysSettingService.setting();
        if(setting != null){
            return  Result.success(setting);
        }
        return Result.error("返回错误");
    }

    /**
     * 登录验证
     * @param request
     * @param systemUserDTO
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "登陆接口")
    @PostMapping("/login")
    public Map<String,Object> login(HttpServletRequest request, @RequestBody SystemUserDTO systemUserDTO)throws Exception{
        HttpSession session = request.getSession();
        String username = systemUserDTO.username;
        String password = systemUserDTO.password;
        String code = systemUserDTO.code;
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        sysUser.setPassword(MD5Util.MD5(password));
        SysUser model =  sysUserService.verifyUserNameAndPassWord(sysUser);
        if(model == null){
            Map<String,Object> data = new HashMap<>();
            data.put("code","400");
            data.put("msg","账号或者密码错误");
            return data;
        }
        if(!VerifyValidateUtil.verifyValidate(session,code)){
            Map<String,Object> data = new HashMap<>();
            data.put("code","400");
            data.put("msg","验证码错误");
            return data;
        }
        session.setAttribute("sysUser",model);
        String token = JwtUtil.createToken(model.getUserId().toString(), model.getUsername());
        LocalDateTime localDateTime = LocalDateTime.now().plusHours(1);
        Map<String,Object> data = new HashMap<>();
        data.put("code",200);
        data.put("expire",localDateTime.toString());
        data.put("token",token);
        return data;
    }

    @ApiOperation(value = "登陆接口")
    @PostMapping("/api/v1/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        Cookie cookie = CookiesUtil.getCookieByName(request, "Admin-Token");
        CookiesUtil.setCookie(response,"Admin-Token",cookie.getValue(),0);
        session.removeAttribute("sysUser");
        return Result.success();
    }

    @RequestMapping("/api/v1/getinfo")
    public Result login(HttpServletRequest request)throws Exception{
        Map<String, Object> data = loginService.getinfo(request);
        return Result.success(data);
    }

}
